package com.xuan.bkm.security.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.xuan.bkm.entity.Admin;

import java.util.Date;

public class TokenUtil {
    private static volatile TokenUtil instance;
    private TokenUtil(){
    }

    public static TokenUtil getInstance(){
        if(instance==null){
            synchronized (TokenUtil.class){
                if(instance==null){
                    instance=new TokenUtil();
                }
            }
        }
        return instance;
    }


    public String createToken(Admin admin){
        String token= JWT.create()
                .withAudience(admin.getNum())
                .withExpiresAt(new Date(System.currentTimeMillis()+1000*1))
                .withClaim("ip","192.168.0.158")
                .withClaim("time",new Date(System.currentTimeMillis()))
                .sign(Algorithm.HMAC256(admin.getPassword()));
        return token;
    }

    public String getAudit(String token){
        return JWT.decode(token).getAudience().get(0);
    }

    public static void main(String[] args) {
        Admin admin=new Admin();
        admin.setNum("dyit01");
        admin.setPassword("123");
        String token=TokenUtil.getInstance().createToken(admin);
        System.out.println(token);
        System.out.println(TokenUtil.getInstance().getAudit(token));
    }
}
